<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="/static/css/index.css"/>
    <link rel="stylesheet" type="text/css" href="/static/layer/theme/default/layer.css">
    <script src="/static/js/jquery-3.2.1.min.js"></script>
    <script src="/static/js/axios.min.js"></script>
    <script src="/static/js/vue.global.js"></script>
    <script src="/static/layer/layer.js"></script>
    <title>资源上传</title>
</head>
<body>
    {% include 'commonNav.html' %}
	
	<article>
		<!-- 网站主体 -->
		<div id="main">
			<section class="ct">
				<!-- 上传表单-->
				<div class="upload">
					<h1>上传资源<em>声明：请确保您上传的内容合法合规，涉及侵权内容将会被移除，详见<a>《爱下载资源共享规则》</a></em></h1>

						<p class="file">
							<input type="file" name="resource" @change="uploadResource">
							<span class="t1" v-if="resource.file == null">点击上传、文件小于1000MB（请不要上传存在侵权的资源哦！）</span>
							<!-- 上传后的效果 -->
							<span class="t2" v-else>
								<img :src="extensions" />
								<b v-text="resource.name"></b>
								<progress :value="startNum" max="100" v-if="show"></progress>
								<a>重新上传</a>
							</span> 

						</p>
						
						<p>
							<label><em>*</em>资源名称：</label>
							<input class="upt" type="text" name="resourceName" v-model.trim="resource.name" placeholder="请输入资源名" />
							<em></em> <!-- 显示错误信息  -->
						</p>
						
						<p>
							<label>资源描述：</label>
							<textarea  class="area" v-model.trim="res.descript"
								placeholder="简要介绍一下资源内容"></textarea>
						</p>
						
						<p>
							<label><em>*</em>关键词：</label>
							<span class="key-tag">
								<a class="key">
									<span v-for="(item, index) in res.keywords"
                                          @click="res.keywords.splice(index, 1)"
                                          :key="item" v-text="item"></span>
									<!-- 单击添加标签后、产生的效果 -->
									<input type="text" v-if="isKey" v-focus @keydown.enter="addKeywords"/>
								</a>
								<span class="key-tag-msg">
									<button type="button" class="keywords add"
                                            v-if="res.keywords.length < 5 && !isKey"
                                            @click.stop.prevent="isKey = true">添加标签</button>
									<i class="lb">按回车键创建标签</i>
								</span>
							</span>
							
							<span class="source-tag-msg">最多添加5个标签，每个标签不超过16个字</span>
						</p>
						
						<div class="source-type-div">
							<p>
								<label>所属分类：</label>
								<select class="upt source-type source-type-down" v-model="res.catalog">
                                    {% for catalog in catalogs %}
                                        <optgroup label="{{ catalog.name }}">
                                            {% for sub_catalog in catalog.active_sub_catalogs %}
                                                <option value="{{ sub_catalog.pk }}">{{ sub_catalog.name }}</option>
                                            {% endfor %}
                                        </optgroup>
                                    {% endfor %}
								</select>
							</p>
						</div>
						
						<p>
							<label><em>*</em>资源分：</label>
							<select class="upt" id="sel" name="score" v-model="res.score">
								<option selected="selected">0</option>
								<option>1</option>
								<option>2</option>
								<option>3</option>
								<option>4</option>
								<option>5</option>
							</select>
						</p>
						
						<p>
                        <label>验证码：</label>
                        <input id="code" class="upt captcha" type="text" name="code" v-model="res.code"
                               value="" placeholder="请输入验证码,如果看不清，点击验证码进行刷新"/>
                        <img ref="captchaImg" class="captcha" title="看不清点击刷新" src="/res/captcha?w=140&h=40"
                             @click.self="$event.target.src = '/res/captcha?w=140&h=40&_=' + Math.random()"
                              style="cursor: pointer"/>
                        <em></em>
                    </p>
						
						<p><label class="btn"><a class="btn" @click="handleUpload">提交</a></label></p>
				</div>
			</section>
		</div>
	</article>
	
	<footer>
		<p class="decro">本站所有资源信息均由网友上传,本站只是为了推广资源让更多读者下载,使用。如涉侵权，请联系管理员</p>
		<p class="cr">Copyright © 2021-2025 <span class="site">爱下载资源分享平台</span> All Rights Reserved.</p>
		<p class="num">沪ICP备14048333号</p>
	</footer>

</body>

<script>
Vue.createApp({
    data() {
        return {
            resource: {
                file: null , // 存储上传的文件
                name: '' , // 存储上传的文件名
                size: 0, // 设置上传文件的大小
                ext: '', // 存储上传的文件扩展名
            } ,
            startNum: 0, // 上传进度
            show: true, // 是否显示进度条,
            res: {
                url: null , // 资源存储路径
                descript: "", // 资源描述
                code: "" , // 验证码
                score: 0, // 资源积分
                catalog: null, // 资源分类
                keywords: [], // 关键字
            },
            isKey: false, // 是否显示关键字输入框
        }
    },
    methods: {
        handleUpload(){
            if (this.resource.file == null) {
                layer.msg("请选择要上传的资源", {icon: 5})
                return false;
            }
            if (this.res.url == null) {
                layer.msg("资源上传中，请稍后", {icon: 5})
                return false;
            }
            if (!this.resource.name) {
                layer.msg("请输入资源名称", {icon: 5})
                return false;
            }
            if (this.res.keywords.length === 0) {
                layer.msg("请至少输入1个关键子", {icon: 5})
                return false;
            }
            if (!this.res.catalog) {
                layer.msg("请选择资源分类", {icon: 5})
                return false;
            }
            if (!this.res.code) {
                layer.msg("请输入验证码", {icon: 5})
                return false;
            }
            // 提交上传资源请求
            axios.post('/res/upload', {
                name: this.resource.name,
                url: this.res.url,
                descript: this.res.descript,
                score: this.res.score,
                catalog: this.res.catalog,
                keywords: this.res.keywords.join("::"),
                code: this.res.code,
                size: this.resource.size,
                ext: this.resource.ext,
            }, {
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                }
            }).then(ret => {
                if (ret.data.code === 200) {
                    layer.msg("资源上传成功", {icon: 6});
                    // 清空表单数据
                    this.resource.file = null ;
                    this.resource.name = "";
                    this.resource.ext = "" ;
                    this.resource.size = 0 ;
                    this.resource.ext = "" ;
                    this.res.url = null ;
                    this.res.descript = "";
                    this.res.score = 0 ;
                    this.res.catalog = null ;
                    this.res.keywords = [] ;
                    this.res.code = "" ;
                    // 获取验证码图片，并点击图片刷新验证码
                    this.$refs.captchaImg.src = '/res/captcha?w=140&h=40&_=' + Math.random()
                } else {
                    layer.msg(ret.data.message, {icon: 5});
                }
            }).catch(error => {
                layer.msg('资源上传失败', {icon: 5})
            })
        },
        uploadResource(event) {
            const file = event.target.files[0] ;
            // 获取上传的文件、并赋值给 响应式数据
            this.resource.file = file;
            this.resource.name = file.name ;
            this.resource.size = file.size ;
            // 获取 文件名 最后一个点出现的索引位置
            let index = file.name.lastIndexOf(".")
            if (index !== -1) {
                this.resource.ext = file.name.substring(index + 1);
            }else{
                this.resource.ext = "" ;
            }
            // 使用异步请求 上传文件到 django 服务器
            this.show = true ;
            this.startNum = 0 ;
            let formData = new FormData();
            formData.append("resource", file);
            axios.post("/res/upload-resource", formData, {
                onUploadProgress: (progressEvent)=>{
                    if (progressEvent.event.lengthComputable) {
                        this.startNum = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                    }
                }
            }).then(ret => {
                if (ret.data.code === 200) {
                    this.startNum = 100;
                    setTimeout(() => this.show = false, 1000)
                    this.res.url = ret.data.url ;
                }
            }).catch(error => {
                layer.msg('资源上传失败')
            })
        },
        addKeywords(event) {
            // 获取输入的关键字
            let keyword = event.target.value.trim();
            if (keyword === "") {
                layer.msg('关键字不允许为空');
                return false;
            }
            // 检查关键字是否已存在
            if (this.res.keywords.includes(keyword)) {
                layer.msg('关键字已存在');
                return false;
            }
            if (keyword.length > 16) {
                layer.msg('关键字不能超过16个字符');
                return false;
            }
            // 添加关键字到数组中
            this.res.keywords.push(keyword);
            this.isKey = false ;
        }
    },
    computed: {
        extensions() {
            const allowExts = ["7z", "avi", "bmp", "doc", "docx", "exe", "gif", "gz", "html", "md", "mp4", "pdf", "png", "ppt", "pptx", "rar", "rmvb", "txt", "xls", "xlsx", "zip", "wps"];
            let ext = "unknow" ;
            if (allowExts.includes(this.resource.ext)) {
                ext = this.resource.ext
            }
            return "/static/images/" + ext + ".svg" ;
        }
    },
    directives: {
        focus: {
            mounted(el, binding, vnode) {
                // dom 节点挂在后 触发
                el.focus();
            }
        }
    }
}).mount("#main")

</script>

</html>